package se19team1e.util;

/**
 * 
 * A helper utility class for float operations.
 * 
 * @author lai shiaw san
 *
 */
public class FloatUtil {

    /**
     * Checks if a string is a valid float value.
     * <p>
     * The string is trimmed of whitespace before converting.
     * </p>
     * @param s String to check.
     * @return True if the string is a valid float value.
     */
    public static boolean isFloat( String s ) {
        // treat null as empty string
        if ( s == null ) {
            s = "";
        }
        // trim string
        s = s.trim();
        try {
            Float.parseFloat( s );
            return true;
        } catch ( NumberFormatException e ) {
            return false;
        }
    }

    /**
     * Converts a string to a float value.
     * <p>
     * The string is trimmed of whitespace before converting.
     * </p>
     * <p>
     * Invalid values are treated as 0.
     * </p>
     * @param s String to convert.
     * @return Converted value if possible, otherwise 0.
     */
    public static float toFloat( String s ) {
        // treat null as empty string
        if ( s == null ) {
            s = "";
        }
        // trim string
        s = s.trim();
        try {
            return Float.parseFloat( s );
        } catch ( NumberFormatException e ) {
            return 0;
        }
    }
    
}
